package com.houdoudou.affair.app;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Templates;
















import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.houdoudou.affair.jsp.Common;
import com.houdoudou.bean.AppBack;
import com.houdoudou.bean.Branch;
import com.houdoudou.bean.Customer;
import com.houdoudou.bean.Distribute;
import com.houdoudou.bean.Machine;
import com.houdoudou.bean.Order;
import com.houdoudou.bean.OrderProduct;
import com.houdoudou.bean.PasswordUtil;
import com.houdoudou.bean.Refund;
import com.houdoudou.bean.Sort;
import com.houdoudou.bean.Product;
import com.houdoudou.bean.Supplier;
import com.houdoudou.bean.TransPasswordUtil;
import com.houdoudou.common.CommonFileFunction;
import com.houdoudou.common.CommonJSON;
import com.houdoudou.common.CommonMathFunction;
import com.houdoudou.common.Constant;
import com.houdoudou.common.DateTimeFunction;
import com.houdoudou.dao.BranchDao;
import com.houdoudou.dao.ConnFactory;
import com.houdoudou.dao.CustomerDao;
import com.houdoudou.dao.DistributeDao;
import com.houdoudou.dao.MachineDao;
import com.houdoudou.dao.OrderDao;
import com.houdoudou.dao.OrderProductDao;
import com.houdoudou.dao.RefundDao;
import com.houdoudou.dao.SortDao;
import com.houdoudou.dao.ProductDao;
import com.houdoudou.dao.SupplierDao;

public class SupplierAffairApp1 {

/*------------------------------------------商家登陆-------------------------------------------------*/	
	
	public static void login(HttpServletRequest req, HttpServletResponse resp) throws IOException{		
	
		Supplier supplier = null;
		
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 JSONObject temp= JSONObject.fromObject(jsonData);
		 supplier= (Supplier) JSONObject.toBean(temp, Supplier.class);
		 Supplier.print("after supplier app login ", supplier);
		// supplier= Supplier.encrypt(supplier);
		 if(supplier.getTelnum().isEmpty()) { 
			new AppBack(req,resp, false, "传入参数不对").send("", "");
		    return;}
		 }catch(Exception e2){
			 e2.printStackTrace();		 			
			    return ;
		 }
	
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();
		  
		   SupplierDao supplierDao= new  SupplierDao(conn);	  
			Supplier supplierExist=  supplierDao.selectById(supplier.getTelnum());
			if(supplierExist.getTelnum().isEmpty()){
				new AppBack(req,resp, false, "用户不存在").send("", "");
				 return;
				
			}else{
				 supplierExist= Supplier.decrypt(supplierExist);
				 supplierExist= Supplier.transEncrypt(supplierExist);
				if(supplierExist.getSecret().equals(supplier.getSecret())){
					String  cipertext=TransPasswordUtil.encrypt(supplierExist.getSecret());
					JSONObject supplierJO= JSONObject.fromObject(supplierExist);
					new AppBack(req,resp, supplierJO,true, "登陆成功").send("supplier", "");
					 return;
				}else{
					new AppBack(req,resp, false, "密码错误").send("", "");
					 return;
				}		  
			}
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp, false, "数据库异常").send("", "");
			 return;
			
		}finally{
			 ConnFactory.closeConn(conn);	
				
		}
				 
	}
	
/*------------------------------------------新建目录-------------------------------------------------*/
	
	public static void createIndex(HttpServletRequest req, HttpServletResponse resp){
		
		Sort sort;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
		 JSONObject temp= JSONObject.fromObject(jsonData);
		 sort= (Sort) JSONObject.toBean(temp, Sort.class);	
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
		//调用 dao处理事务 -------------------------
				Connection conn = null;	
				try{
				   conn= ConnFactory.getConn();
				   conn.setAutoCommit(false);
				   SortDao sortDao= new  SortDao(conn);	  
					 int id=  sortDao.create(sort); 
					  sort.setId(id);	
					  conn.commit();
					  new AppBack(req,resp,JSONObject.fromObject(sort), true, "创建成功").send("sort", "");
				      return;
				}catch(Exception e){
					e.printStackTrace();
					try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
					new AppBack(req,resp, false, "数据库异常").send("", "");
				}finally{
					 ConnFactory.closeConn(conn);					
				}
	}
	
	
	
	
/*------------------------------------------搜索分类-------------------------------------------------*/	
	
	public static void searchIndex(HttpServletRequest req, HttpServletResponse resp){		
		
		String  errorInfo=null;
		//获取Bean---------------------------		
		Sort sort;
		JSONObject sortJO;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println("jsonData="+jsonData);
		 sortJO = JSONObject.fromObject(jsonData);
		 sort= (Sort) JSONObject.toBean(sortJO, Sort.class);	
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
	//	sort.setTelnum(req.getParameter("telnum"));
		// 初始化搜索结果
		 List<Sort> sortes = new ArrayList<Sort>();
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();  
		   SortDao sortDao= new  SortDao(conn);
		   String sql=SortDao.getSearchSql(sort);
		   System.out.println(sql);
		   sortes= sortDao.search(sql);	  		   
		   JSONArray sortesJA= JSONArray.fromObject(sortes);
		   new AppBack(req,resp,sortJO,sortesJA ,true,"搜索成功").send("sort", "sorts");
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp, false, "数据库异常").send("", "");
			return;
		}finally{
			 ConnFactory.closeConn(conn);	
		}
		
	//处理事务结果，赋值----------------------
	
   }
/*------------------------------------------删除分类-------------------------------------------------*/	
	
	public static void deleteIndex(HttpServletRequest req, HttpServletResponse resp){		
		
		String  errorInfo=null;
		//获取Bean---------------------------		
		Sort sort;
		JSONObject sortJO;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println("jsonData="+jsonData);
		 sortJO = JSONObject.fromObject(jsonData);
		 sort= (Sort) JSONObject.toBean(sortJO, Sort.class);	
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
	
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();  
		   SortDao sortDao= new  SortDao(conn);
		    sortDao.delete(sort);
		   new AppBack(req,resp,sortJO,true,"删除成功").send("sort", "");
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp, false, "数据库异常").send("", "");
			return;
		}finally{
			 ConnFactory.closeConn(conn);	
		}	
      }
	
/*------------------------------------------更新目录-------------------------------------------------*/
	
	public static void updateIndex(HttpServletRequest req, HttpServletResponse resp){
		
		Sort sort;
		JSONObject sortJO;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
		  sortJO= JSONObject.fromObject(jsonData);
		 sort= (Sort) JSONObject.toBean(sortJO, Sort.class);	
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
		//调用 dao处理事务 -------------------------
				Connection conn = null;	
				try{
				   conn= ConnFactory.getConn();
				   conn.setAutoCommit(false);
				   SortDao sortDao= new  SortDao(conn);	  
					  sortDao.update(sort); 					 	
					  conn.commit();
					  new AppBack(req,resp,sortJO, true, "更新成功").send("sort", "");
				      return;
				}catch(Exception e){
					e.printStackTrace();
					try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
					new AppBack(req,resp, false, "数据库异常").send("", "");
				}finally{
					 ConnFactory.closeConn(conn);					
				}
	}
/*------------------------------------------新建产品-------------------------------------------------*/
	
	public static void createProduct(HttpServletRequest req, HttpServletResponse resp){
		
		Product product;
		List<Branch> branches;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
		 JSONObject temp= JSONObject.fromObject(jsonData);
		JSONArray branchesJA= (JSONArray) temp.remove("branches");
		System.out.println(branchesJA.toString());
		System.out.println(temp.toString());
		 product= (Product) JSONObject.toBean(temp, Product.class);	
		 branches= JSONArray.toList(branchesJA, Branch.class);		
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
		//调用 dao处理事务 -------------------------
				Connection conn = null;	
				try{
				   conn= ConnFactory.getConn();
				   conn.setAutoCommit(false);
				   ProductDao productDao= new  ProductDao(conn);	  
					 int id=  productDao.create(product); 
					  product.setId(id);	
					  
					  for(int i=0;i<branches.size();i++){
						  branches.get(i).setProduct(id);
					  }
					  BranchDao branchDao= new BranchDao(conn);
					  branchDao.create(branches);
					  String PicBaseAddress=CommonFileFunction.getPicBaseAddress();
					 String dir=PicBaseAddress+product.getOwner()+"/"+product.getSupplier()+"/"+product.getId()+"/";
				     product.setDir(dir);
					 productDao.update(product);
					 conn.commit();
					  new AppBack(req,resp,JSONObject.fromObject(product), true, "创建成功").send("product", "");
				      return;
				}catch(Exception e){
					e.printStackTrace();
					try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
					new AppBack(req,resp, false, "数据库异常").send("", "");
				}finally{
					 ConnFactory.closeConn(conn);					
				}
	}
		
	

	
/*------------------------------------------搜索产品-------------------------------------------------*/	
	
	public static void searchProduct(HttpServletRequest req, HttpServletResponse resp){		
		
		String  errorInfo=null;
		//获取Bean---------------------------		
		Product product;
		JSONObject productJO,backJO;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println("jsonData="+jsonData);
		 productJO = JSONObject.fromObject(jsonData);
		 product= (Product) JSONObject.toBean(productJO, Product.class);	
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
	//	product.setTelnum(req.getParameter("telnum"));
		// 初始化搜索结果
		 List<Product> products = new ArrayList<Product>();
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();  
		   ProductDao productDao= new  ProductDao(conn);
		   String sql=ProductDao.getSearchSql(product);
		   System.out.println(sql);
		   products= productDao.search(sql);	  		   
		   JSONArray productsJA= JSONArray.fromObject(products);
		   for(int i=0;i<products.size();i++){
			  
			   Sort sort= new Sort(); sort.setId(products.get(i).getSort());
			   sort= new SortDao(conn).selectById(sort);
			   if(sort==null){ productsJA.getJSONObject(i).put("sortname", "已删除分类");}else{
			   productsJA.getJSONObject(i).put("sortname", sort.getName());}
			   
			   Branch branch = new Branch(); branch.setProduct(products.get(i).getId());
			    List<Branch> branches= new BranchDao(conn).search(BranchDao.getSearchSql(branch));
			    productsJA.getJSONObject(i).put("branches", JSONArray.fromObject(branches));
			   
		   }
		  
		   new AppBack(req,resp,productJO,productsJA ,true,"搜索成功").send("product", "products");
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp, false, "数据库异常").send("", "");
			return;
		}finally{
			 ConnFactory.closeConn(conn);	
		}
		
	//处理事务结果，赋值----------------------
	
   }
/*------------------------------------------删除产品-------------------------------------------------*/	
	
	public static void deleteProduct(HttpServletRequest req, HttpServletResponse resp){		
		
		String  errorInfo=null;
		//获取Bean---------------------------		
		Product product;
		JSONObject productJO;
		//获取Bean---------------------------
		try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println("jsonData="+jsonData);
		 productJO = JSONObject.fromObject(jsonData);
		 product= (Product) JSONObject.toBean(productJO, Product.class);	
		 
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
	
		//调用 dao处理事务 -------------------------
		Connection conn = null;
		try{
		   conn= ConnFactory.getConn();  
		   conn.setAutoCommit(false);
		    ProductDao productDao= new  ProductDao(conn);
		    productDao.delete(product);
		    new BranchDao(conn).delete(product.getId());
		    CommonFileFunction.deletePic(product.getDir());
		   new AppBack(req,resp,productJO,true,"删除成功").send("product", "");
		   conn.commit();
		}catch(Exception e){
			e.printStackTrace();
			new AppBack(req,resp, false, "数据库异常").send("", "");
			try {conn.rollback();} catch (SQLException e1) {	e1.printStackTrace();	}
			return;
		}finally{
			 ConnFactory.closeConn(conn);	
		}	
      }	
	
/*------------------------------------------更新产品-------------------------------------------------*/
	
	public static void updateProduct(HttpServletRequest req, HttpServletResponse resp){
		
		Product product;
		JSONObject productJO;
		List<Branch> branches;
		//获取Bean---------------------------
		try{
			 String jsonData= req.getParameter("jsonData");
			 System.out.println(jsonData);
		    productJO= JSONObject.fromObject(jsonData);
			JSONArray branchesJA= (JSONArray) productJO.remove("branches");
			System.out.println(branchesJA.toString());
			System.out.println(productJO.toString());
			 product= (Product) JSONObject.toBean(productJO, Product.class);
			 
			 branches= JSONArray.toList(branchesJA, Branch.class);		
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
		//调用 dao处理事务 -------------------------
				Connection conn = null;	
				try{
				   conn= ConnFactory.getConn();
				   conn.setAutoCommit(false);
				   ProductDao productDao= new  ProductDao(conn);
				     BranchDao branchDao= new BranchDao(conn);
					  productDao.update(product); 	
					
					  branchDao.delete(product.getId());
					  for(int i=0;i<branches.size();i++){
						  branches.get(i).setProduct(product.getId());
					  }
					  branchDao.create(branches);
					  CommonFileFunction.deletePic(product.getDir());
					  conn.commit();
					  new AppBack(req,resp,productJO, true, "更新成功").send("product", "");
				      return;
				}catch(Exception e){
					e.printStackTrace();
					try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
					new AppBack(req,resp, false, "数据库异常").send("", "");
				}finally{
					 ConnFactory.closeConn(conn);					
				}
	}
/*------------------------------------------搜索当前订单-------------------------------------------------*/
	
	public static void searchOrder(HttpServletRequest req, HttpServletResponse resp){
		
		Supplier supplier;
		Order order;
		
		//获取Bean---------------------------
		try{
			 String jsonData= req.getParameter("jsonData");
			 System.out.println(jsonData);
		    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
		    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
		    JSONObject  orderJO=jsonJO.getJSONObject("order");
			 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
			 order= (Order) JSONObject.toBean(orderJO, Order.class);
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
		//调用 dao处理事务 -------------------------
				Connection conn = null;	
				try{
				   conn= ConnFactory.getConn();
				   if(! isSupplierValid(conn, supplier)){ 
					   new AppBack(req,resp, false, "商家验证失败").send("", ""); return;}
				      
				          OrderDao orderDao= new OrderDao(conn);
				          OrderProductDao orderProductDao= new OrderProductDao(conn);
				          List<Order> orders= orderDao.search(OrderDao.getSearchSql(order));
				          JSONArray orderJA= new JSONArray();
				           for(int i=0;i<orders.size();i++){
				        	List<OrderProduct>  orderProducts=  orderProductDao.selectById(orders.get(i).getId());
				        	   JSONObject orderTempJO= JSONObject.fromObject(orders.get(i));
				        	   orderTempJO.put("products", JSONArray.fromObject(orderProducts));
				        	   
				        	   if(orders.get(i).getIsRefund()==2){
									  Refund refund=new RefundDao(conn).selectById(orders.get(i).getId());  
									  orderTempJO.put("refund", JSONObject.fromObject(refund));
									  }
				        	   
				        	   orderJA.add(orderTempJO);
				           }
				          
					  new AppBack(req,resp,orderJA, true, "搜索成功").send("", "orders");
				      return;
				}catch(Exception e){
					e.printStackTrace();
					try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
					new AppBack(req,resp, false, "数据库异常").send("", "");
				}finally{
					 ConnFactory.closeConn(conn);					
				}
	}
		
public static void searchDistribute(HttpServletRequest req, HttpServletResponse resp){
		
		Supplier supplier;
		Distribute distribute;
		
		//获取Bean---------------------------
		try{
			 String jsonData= req.getParameter("jsonData");
			 System.out.println(jsonData);
		    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
		    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
		    JSONObject  distributeJO=jsonJO.getJSONObject("distribute");
			 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
			 distribute=  (Distribute) JSONObject.toBean(distributeJO, Distribute.class);
		 }catch(Exception e2){
			 e2.printStackTrace();			
				new AppBack(req,resp, false, "数据解析错误").send("", "");
			    return ;
		 }
		//调用 dao处理事务 -------------------------
				Connection conn = null;	
				try{
				   conn= ConnFactory.getConn();
				   if(! isSupplierValid(conn, supplier)){ 
					   new AppBack(req,resp, false, "商家验证失败").send("", ""); return;}
				      
				         DistributeDao distributeDao= new DistributeDao(conn);
				         MachineDao machineDao= new MachineDao(conn);
				      List<Distribute> distributes=  distributeDao.search(DistributeDao.getSearchSql(distribute));
				          JSONArray distributeJA= new JSONArray();
				           for(int i=0;i< distributes.size();i++){
				        	     Machine machine= machineDao.selectById(distributes.get(i).getMachine());                 
				        	   JSONObject distributeTempJO= JSONObject.fromObject(distributes.get(i));
				        	   distributeTempJO.put("MACHINE", JSONObject.fromObject(machine));
				        	   distributeJA.add(distributeTempJO);
				           }
				          
					  new AppBack(req,resp,distributeJA, true, "搜索成功").send("", "distributes");
				      return;
				}catch(Exception e){
					e.printStackTrace();
					
					new AppBack(req,resp, false, "数据库异常").send("", "");
				}finally{
					 ConnFactory.closeConn(conn);					
				}
	}
	

/*------------------------------------------搜索当前订单-------------------------------------------------*/


public static void  changeOrderState(HttpServletRequest req, HttpServletResponse resp){
	
	Supplier supplier;
	List<Order> orders;
	
	//获取Bean---------------------------
	try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
	    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
	    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
	    JSONArray  orderJA=jsonJO.getJSONArray("orders");
		 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
		 orders=  JSONArray.toList(orderJA, Order.class);
	 }catch(Exception e2){
		 e2.printStackTrace();			
			new AppBack(req,resp, false, "数据解析错误").send("", "");
		    return ;
	 }
	//调用 dao处理事务 -------------------------
			Connection conn = null;	
			try{
			   conn= ConnFactory.getConn();
			   if(! isSupplierValid(conn, supplier)){ 
				   new AppBack(req,resp, false, "商家验证失败").send("", ""); return;}
			      
			          OrderDao orderDao= new OrderDao(conn);

			         String errorInfo="";
			           for(int i=orders.size()-1;i>=0;i--){
			        	   try{
			        	   orderDao.update(OrderDao.getUpdateSql(orders.get(i)));
			        	   errorInfo+=orders.get(i).getId()+"OK ";
			        	   }catch(Exception e){
			        		   errorInfo+=orders.get(i).getId()+"Failed  ";
			        		   orders.remove(i);
			        	   } 
			           }
			           JSONArray orderJA= JSONArray.fromObject(orders);
				  new AppBack(req,resp,orderJA, true, "搜索成功").send("", "orders");
			      return;
			}catch(Exception e){
				e.printStackTrace();
				try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
				new AppBack(req,resp, false, "数据库异常").send("", "");
			}finally{
				 ConnFactory.closeConn(conn);					
			}
}

/*------------------------------------------拒绝订单-------------------------------------------------*/


public static void  refuseOrder(HttpServletRequest req, HttpServletResponse resp){
	
	Supplier supplier;
	List<Order> orders;
	
	//获取Bean---------------------------
	try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
	    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
	    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
	    JSONArray  orderJA=jsonJO.getJSONArray("orders");
		 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
		 orders=  JSONArray.toList(orderJA, Order.class);
	 }catch(Exception e2){
		 e2.printStackTrace();			
			new AppBack(req,resp, false, "数据解析错误").send("", "");
		    return ;
	 }
	//调用 dao处理事务 -------------------------
			Connection conn = null;	
			try{
			   conn= ConnFactory.getConn();
			   conn.setAutoCommit(false);
			   if(! isSupplierValid(conn, supplier)){ 
				   new AppBack(req,resp, false, "商家验证失败").send("", ""); return;}
			      
			          OrderDao orderDao= new OrderDao(conn);
			        CustomerDao  customerDao= new CustomerDao(conn);
			         String errorInfo="";
			           for(int i=orders.size()-1;i>=0;i--){
			        	   try{
			        		   Order orderExist= orderDao.selectById(orders.get(i).getId());
			        		   if(orderExist.getState()!=10){//已支付
			        			   errorInfo+=orders.get(i).getId()+"Failed  ";
				        		   orders.remove(i);
			        		   } 
			        		   orders.get(i).setDateTimeRF(DateTimeFunction.myDateFormat(new Date()));
			        		   orders.get(i).setState(5);
			        	   orderDao.update(OrderDao.getUpdateSql(orders.get(i)));        	  
			        	
			        	   // ，退款给客户
			        	    Customer customerExist= customerDao.selectById(orders.get(i).getCustomerTelnum());
						    customerExist.setMoney(customerExist.getMoney()+ orders.get(i).getMoneyCu());
						    customerDao.update(customerExist);	
						    //释放箱格，
						    //通知自提柜
						    //通知消费者
						    errorInfo+=orders.get(i).getId()+"OK ";
			        	   }catch(Exception e){
			        		   errorInfo+=orders.get(i).getId()+"Failed  ";
			        		   orders.remove(i);
			        	   } 
			           }
			           JSONArray orderJA= JSONArray.fromObject(orders);
			           conn.commit();
				  new AppBack(req,resp,orderJA, true, "搜索成功").send("", "orders");
			      return;
			}catch(Exception e){
				e.printStackTrace();
				try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
				new AppBack(req,resp, false, "数据库异常").send("", "");
			}finally{
				 ConnFactory.closeConn(conn);					
			}
}

/*------------------------------------------打印订单-------------------------------------------------*/


public static void  printOrder(HttpServletRequest req, HttpServletResponse resp){
	
	Supplier supplier;
	List<Order> orders;
	
	//获取Bean---------------------------
	try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
	    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
	    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
	    JSONArray  orderJA=jsonJO.getJSONArray("orders");
		 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
		 orders=  JSONArray.toList(orderJA, Order.class);
	 }catch(Exception e2){
		 e2.printStackTrace();			
			new AppBack(req,resp, false, "数据解析错误").send("", "");
		    return ;
	 }
	//调用 dao处理事务 -------------------------
			Connection conn = null;	
			try{
			   conn= ConnFactory.getConn();
			   conn.setAutoCommit(false);
			   if(! isSupplierValid(conn, supplier)){ 
				   new AppBack(req,resp, false, "商家验证失败").send("", ""); return;}
			      
			          OrderDao orderDao= new OrderDao(conn);
			     
			         String errorInfo="";
			           for(int i=orders.size()-1;i>=0;i--){
			        	   try{
			        		   Order orderExist= orderDao.selectById(orders.get(i).getId());
			       		
			        		   orders.get(i).setPrintTimes((orderExist.getPrintTimes()+1));
			        	   orderDao.update(OrderDao.getUpdateSql(orders.get(i)));        	  
		        	   
						    errorInfo+=orders.get(i).getId()+"OK ";
			        	   }catch(Exception e){
			        		   errorInfo+=orders.get(i).getId()+"Failed  ";
			        		   orders.remove(i);
			        	   } 
			           }
			           JSONArray orderJA= JSONArray.fromObject(orders);
			           conn.commit();
				  new AppBack(req,resp,orderJA, true, errorInfo).send("", "orders");
			      return;
			}catch(Exception e){
				e.printStackTrace();
				try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
				new AppBack(req,resp, false, "数据库异常").send("", "");
			}finally{
				 ConnFactory.closeConn(conn);					
			}
}
/*------------------------------------------搜索当前订单-------------------------------------------------*/

public static void searchRefund(HttpServletRequest req, HttpServletResponse resp){
	
	Supplier supplier;
	Refund refund;
	JSONObject backJO= new JSONObject();
	//获取Bean---------------------------
	try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
	    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
	    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
	    JSONObject refundJO=jsonJO.getJSONObject("refund");
		 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
		 refund= (Refund) JSONObject.toBean(refundJO, Refund.class);
	 }catch(Exception e2){
		 e2.printStackTrace();			
			new AppBack(req,resp).send(1, "数据解析错误");
		    return ;
	 }
	//调用 dao处理事务 -------------------------
			Connection conn = null;	
			try{
			   conn= ConnFactory.getConn();
			   if(! isSupplierValid(conn, supplier)){ 
				   new AppBack(req,resp).send(1, "商家验证失败"); return;}
			   
			          OrderDao orderDao= new OrderDao(conn);
			          OrderProductDao orderProductDao= new OrderProductDao(conn);
			          RefundDao refundDao= new RefundDao(conn);
			          List<Refund> refunds= refundDao.search(RefundDao.getSearchSql(refund));
			       
			          JSONArray orderJA= new JSONArray();
			          
			           for(int i=0;i<refunds.size();i++){
			        		Order order= orderDao.selectById(refunds.get(i).getOrderID()); 
			        	List<OrderProduct>  orderProducts=  orderProductDao.selectById(order.getId());
			        	
			        	   JSONObject orderTempJO= JSONObject.fromObject(order);
			        	   orderTempJO.put("products", JSONArray.fromObject(orderProducts));			        
			        	   orderTempJO.put("refund", JSONObject.fromObject(refunds.get(i)));
			        	 			        	   
			        	   orderJA.add(orderTempJO);
			           }
			           backJO.put("orders", orderJA);
				  new AppBack(req,resp,backJO).send(2, "搜索成功");
			      return;
			}catch(Exception e){
				e.printStackTrace();
				new AppBack(req,resp).send(1, "数据库异常");
			}finally{
				 ConnFactory.closeConn(conn);					
			}
}
	
/*------------------------------------------同意退款-------------------------------------------------*/

public static void agreeRefund(HttpServletRequest req, HttpServletResponse resp){
	

	Supplier supplier;
	List<Order> orders;
	JSONObject backJO= new JSONObject();
	//获取Bean---------------------------
	try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
	    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
	    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
	    JSONArray  orderJA=jsonJO.getJSONArray("orders");
		 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
		 orders=  JSONArray.toList(orderJA, Order.class);
	 }catch(Exception e2){
		 e2.printStackTrace();			
		 new AppBack(req,resp).send(1,"传入数据解析异常");
		    return ;
	 }
	//调用 dao处理事务 -------------------------
			Connection conn = null;	
			try{
			   conn= ConnFactory.getConn();
			   if(! isSupplierValid(conn, supplier)){ 
				   new AppBack(req,resp).send(1, "商家验证失败"); return;}
			   
			          RefundDao refundDao= new RefundDao(conn);
			          CustomerDao customerDao= new CustomerDao(conn);
			          OrderDao orderDao= new OrderDao(conn);
			     	      String reultInfo="";    
			     	      conn.setAutoCommit(false);
			           for(int i=orders.size()-1;i>=0;i--){
			        	   try{
			        		   Refund refundExist = refundDao.selectById(orders.get(i).getId());
			        		   long dateTimeSL= Long.parseLong(refundExist.getDateTimeSL());
			        		   boolean isDo=refundExist.getResult()==1; //不能接受
			        		   isDo=isDo&&(refundExist.getState()==1); //要在此状态
			        		   isDo=isDo&&(dateTimeSL> DateTimeFunction.myDateTimeValue(new Date())); //不能超时
			        		   
			        		   if(isDo){
			        			   Refund refund=  new Refund();
				        		   refund.setOrderID(orders.get(i).getId());
				        		   refund.setState(2);
				        		   refund.setDateTimeS(DateTimeFunction.myDateFormat(new Date()));
				        		   refundDao.update(refund);
				        		   
				        		Order orderExist= orderDao.selectById(orders.get(i).getId());
				        		   // ，退款给客户
								 
								    Customer customerExist= customerDao.selectById(orderExist.getCustomerTelnum());
								    customerExist.setMoney(customerExist.getMoney()+ refundExist.getMoney());
								    customerDao.update(customerExist);	
						
								    // 判断，是否释放箱格。	   			 
								    conn.commit();
			        		   }else{  
			        			   reultInfo+="  订单"+orders.get(i).getId()+"同意退款失败：不满足退款条件";
			        			   orders.remove(i);
			        		   }	   
			        	   }catch(Exception e){
			        		   e.printStackTrace();
			        		   reultInfo+="  订单"+orders.get(i).getId()+"同意退款失败：数据库异常";
			        		   orders.remove(i); }
			        	   
			           }   // for 
			          
			           backJO.put("orders", JSONArray.fromObject(orders));
				  new AppBack(req,resp,backJO).send(2,  reultInfo);
			      return;
			}catch(Exception e){
				e.printStackTrace();
				try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
				new AppBack(req,resp).send(1, "数据库异常");
			}finally{
				 ConnFactory.closeConn(conn);					
			}
}


/*------------------------------------------同意退款-------------------------------------------------*/

public static void refuseRefund(HttpServletRequest req, HttpServletResponse resp){
	

	Supplier supplier;
	List<Order> orders;
	JSONObject backJO= new JSONObject();
	//获取Bean---------------------------
	try{
		 String jsonData= req.getParameter("jsonData");
		 System.out.println(jsonData);
	    JSONObject jsonJO= JSONObject.fromObject(jsonData);	
	    JSONObject supplierJO= jsonJO.getJSONObject("supplier");
	    JSONArray  orderJA=jsonJO.getJSONArray("orders");
		 supplier= (Supplier) JSONObject.toBean(supplierJO, Supplier.class);
		 orders=  JSONArray.toList(orderJA, Order.class);
	 }catch(Exception e2){
		 e2.printStackTrace();			
		  new AppBack(req,resp).send(1, "拒绝退款失败，传入参数解析错误");
		    return ;
	 }
	//调用 dao处理事务 -------------------------
			Connection conn = null;	
			 String reultInfo="";  
			try{
			   conn= ConnFactory.getConn();
			   if(! isSupplierValid(conn, supplier)){ 
				   new AppBack(req,resp).send(1, "拒绝退款失败，商家验证失败"); return;}
			   
			          RefundDao refundDao= new RefundDao(conn);
			        
			     	       
			     	      conn.setAutoCommit(false);
			           for(int i=orders.size()-1;i>=0;i--){
			        	   try{
			        		   Refund refundExist = refundDao.selectById(orders.get(i).getId());
			        		   long dateTimeSL= Long.parseLong(refundExist.getDateTimeSL());
			        		   boolean isDo=refundExist.getResult()==1; //未结束
			        		   isDo=isDo&&(refundExist.getState()==1); //在状态 
			        		   isDo=isDo&&(dateTimeSL> DateTimeFunction.myDateTimeValue(new Date())); //不超时
			        		   
			        		   if(isDo){
			        			   Refund refund=  new Refund();
				        		   refund.setOrderID(orders.get(i).getId());
				        		   refund.setState(4);
				        		   refund.setDateTimeS(DateTimeFunction.myDateFormat(new Date()));
				        		   Date dateTimeCL= DateTimeFunction.addHour(new Date(), Constant.hoursBeforCustomerDealRefund);
				        		   refund.setDateTimeCL(DateTimeFunction.myDateFormat(dateTimeCL));
				        	       refundDao.update(refund);			        		   				        	 			 
								    conn.commit();
			        		   }else{  
			        			   reultInfo+="  订单"+orders.get(i).getId()+"，拒绝退款失败：不满足退款条件";
			        			   orders.remove(i);
			        		   }	   
			        	   }catch(Exception e){
			        		   e.printStackTrace();
			        		   reultInfo+="  订单"+orders.get(i).getId()+"，拒绝退款失败：数据库异常";
			        		   orders.remove(i); }
			        	   
			           }   // for 
			          
			           backJO.put("orders", JSONArray.fromObject(orders));
				  new AppBack(req,resp,backJO).send(2, reultInfo);
			      return;
			}catch(Exception e){
				e.printStackTrace();
				try {conn.rollback();} catch (SQLException e1) {e1.printStackTrace();}
				new AppBack(req,resp).send(1, "拒绝退款，数据库异常");
			}finally{
				 ConnFactory.closeConn(conn);					
			}
}

	
	/*------------------------------------------验证消费者------------------------------------------------*/	
	public static boolean isSupplierValid(Connection conn,Supplier supplier){
		boolean result=true;
		 SupplierDao supplierDao= new  SupplierDao(conn);	  
			Supplier supplierExist;
			try {
				supplierExist = supplierDao.selectById(supplier.getTelnum());
			if(supplierExist==null){ return false;}
			String secret;
			secret= PasswordUtil.decrypt(supplierExist.getSecret());
			secret=TransPasswordUtil.encrypt(secret);
			supplierExist.setSecret(secret);
				if(supplierExist.getSecret().equals(supplier.getSecret())){
					 return true;
				}else{	 return false;}	
				 }
			 catch (Exception e) {
				e.printStackTrace(); return false;
			}
		
	}	
}
